<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/

jimport( 'joomla.application.component.model' );

/**
 * @package Joomla
 * @subpackage JobBoard
 */
class JAJobBoardModelJASalary extends JModel
{
    var $_data;
    var $_table;
    var $_pagination;
    /**
    * Return the query is used to retrive all row from database
    * @return string The query is used 
    */
    function _buildQuery($limit = 0, $limitstart = 0){
    		
    	global $mainframe, $option;
    	$db =& JFactory::getDBO();
    	$option_1 = $option.'jasalary';
    	$search				= $mainframe->getUserStateFromRequest( $option_1.'.search',              'search',           '',         'string' );
		$filter_order		= $mainframe->getUserStateFromRequest( $option_1.'.filter_order',		'filter_order',		'ordering',	'cmd' );
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( $option_1.'.filter_order_Dir',	'filter_order_Dir',	'ASC',	'word' );
		$filter_state		= $mainframe->getUserStateFromRequest( $option_1.'.filter_state', 'filter_state', '',	'word' );
		
		$search				= JString::strtolower( $search );
		$orderby	= ' ORDER BY '. $filter_order .' '. $filter_order_Dir;
    	$where = ' WHERE 1=1 ';
    	if($search){
    		$where = " AND LOWER(value) like ".$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
    	}
    	if ( $filter_state )
		{
			if ( $filter_state == 'P' ) {
				$where .= ' AND s.published = 1';
			} else if ($filter_state == 'U' ) {
				$where .= ' AND s.published = 0';
			}
		}
        $query = "SELECT   * ".
				 "FROM 	`#__ja_salary` as s ".
				 $where.
				 $orderby;

        return $query;
    }
    
    /**
    * Get data list of email
    * @return array  Array of objects contain email data
    */
    function &getData(){
        // load data if it doesnnot already exists
        if(empty($this->_data)){
            $query = $this->_buildQuery();
            $this->_data = $this->_getList($query);
        }
        
        return $this->_data;
    }
    
    /**
    * Get email table instance
    * @return JTable Email table object
    */
    function &_getTable(){
        if($this->_table == null){
        	$this->_table = &JTable::getInstance('JA_Salary', 'JobBoardTable');
		}
		return $this->_table;
	}
	
	/**
	* Get page navigator object
	* @return 
	*/
	function &getPagination()
	{
		if ($this->_pagination == null) {
			$this->getItems();
		}
		return $this->_pagination;
	}
	
	/**
	* Remove email record
	* @return Number of removed records
	*/
	function remove(){
	    $cid = JRequest::getVar('cid',array(), 'post', 'array');
	    $n =  count($cid);
	    JArrayHelper::toInteger( $cid );
	    
	    if($n){
	        $query = "DELETE FROM #__ja_salary WHERE id = ". implode(" OR id = ", $cid);
	        $db = &JFactory::getDBO();
	        $db->setQuery($query);
	        if($db->query()){
				$row = $this->_getTable();
				$row->reorder();
	            return $n;
			}
		}
		
		return -1;
	}
	
	/**
	* Get email item by ID
	* @return Email Table object
	*/
	function getItem(){
		static $item;
		if (isset($item)) {
			return $item;
		}

		$table =& $this->_getTable();

		// Load the current item if it has been defined
		$edit	= JRequest::getVar('edit',true);
		$cid = JRequest::getVar( 'cid', array(0), '', 'array' );
		JArrayHelper::toInteger($cid, array(0));
		
		if ($edit) {
			$table->load($cid[0]);
		}

	    $item = $table;
	    return $item;	    
	}
	
	/**
	* Get email Item limit row
	* @return Email Table object
	*/
	
	function getItems(){
		global $mainframe, $option;
		
	    $limit				= $mainframe->getUserStateFromRequest( 'global.list.limit',	'limit',$mainframe->getCfg( 'list_limit' ),	'int' );
		$limitstart			= $mainframe->getUserStateFromRequest( $option.'.jasalary.limitstart','limitstart',0,	'int' );
		
		$db = &JFactory::getDBO();
		$query = $this->_buildQuery();
		$db->setQuery($query);
		//print_r($db->getQuery($query));exit;
		$items = $db->loadObjectList();
		
		$total = count( $items );

		jimport('joomla.html.pagination');
		$this->_pagination = new JPagination( $total, $limitstart, $limit );
		
		// slice out elements based on limits
		$list = array_slice( $items, $this->_pagination->limitstart, $this->_pagination->limit );
		
		return $list;
	}
	
    /**
     * Reorder field list item
     *
     * @param int $item    The id of the item
     * @param int $movement Movement direction
     * @return void
     */
    function orderItem($item, $movement){
        global $mainframe;
        
        $row = &$this->_getTable();
        $row->load($item);
        if(!$row->move($movement)){
            $this->setError($row->getError());
            return false;
        }
        return true;
    }
    
    function setOrder($items){
        $total        = count( $items );
        $row        =& $this->_getTable();

        $order        = JRequest::getVar( 'ordering', array(), 'post', 'array' );
        JArrayHelper::toInteger($order);

        // update ordering values
        for( $i=0; $i < $total; $i++ ) {
            $row->load( $items[$i] );
            // track parents
            if ($row->ordering != $order[$i]) {
                $row->ordering = $order[$i];
                if (!$row->store()) {
                    $this->setError($row->getError());
                    return false;
                }
            } // if
        } // for
        
        return true;
    }
    
	/**
	* Checkout item
	* 
	*/
	function checkout($uid = null)
	{
		
		$id = JRequest::getVar('cid', array(0), '', 'array');
		JArrayHelper::toInteger( $id, array(0) );

		// Make sure we have a user id to checkout the article with
		if (is_null($uid)) {
			$user	=& JFactory::getUser();
			$uid	= $user->get('id');
		}

		// Lets get to it and checkout the thing...
		$item	=& $this->getItem();
		if(!$item->checkout($uid, $id[0])) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		
		return true;
	}
	
	/** 
	* Store email item
	* @param array The post array
	*/
	function store(){
	    // Initialize variables
		$db		=& JFactory::getDBO();
		$row	=& $this->getItem();
		$post	= $this->getState('request');
		
		if (!$row->bind( $post )) {
			echo "<script> alert('".$row->getError(true)."'); window.history.go(-1); </script>\n";
			return JText::_("Bind data false");
		}

		if ($row->check() != 'SUCCESS')
		{
			echo "<script> alert('".$row->getError(true)."'); window.history.go(-1); </script>\n";
			return JText::_('Check data failed');
		}

		if (!$row->store())
		{
			echo "<script> alert('".$row->getError(true)."'); window.history.go(-1); </script>\n";
			return JText::_('Store fail');
			//return false;
		}
		$row->reorder();
		$row->checkin();
		return $row->id;
		
	}
	
	function dopublish($publish){
		$db		=& JFactory::getDBO();
		
		$ids = JRequest::getVar('cid', array());		
		$ids = implode( ',', $ids );
		
		$query = "UPDATE #__ja_salary"
		. "\n SET published = " . intval( $publish )
		. "\n WHERE id IN ( $ids )"
		;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		return true;
	}	
}
?>